#!/usr/bin/perl

use DBI;

# This program looks up the hosts from which a 
# given user is allowed to connect.
# Also looks up grants for a user, given the @ symbol in the
# argument list.

$user = $ARGV[0];

# Test to make sure the user entered a username.
if (! $user) {
	print "No user specified.  Usage: <program> <username>\n";
}

$dbh = DBI->connect("DBI:mysql:mysql:",undef,'evh5150');

if (! $dbh) {
        print "Connection failed!!\n\n";
        die();
}

# If there's an @ symbol then the user wants to look up 
# grants.
if ($user =~ m/\@/) {
	($user,$inhost) = split(/\@/, $user);

	# Make sure the username and host are safe to
	# send to MySQL.
	$quoteduser = $dbh->quote($user);
	$quotedhost = $dbh->quote($inhost);
	&priv($user,$inhost);
}
else {
	# User wants to simply lookup the hosts allowed
	# for given username.
	
	# Make sure the username is safe to 
	# send to MySQL.
	$quoteduser = $dbh->quote($user);

	$query = "SELECT host,user FROM user WHERE user = $quoteduser";
	$sth = $dbh->prepare($query);
	$sth->execute();

	while (($host,$username) = ( $sth->fetchrow_array() ) ) {
		if ($host eq '') {
			print "User $user has a blank host entry.\n";
		}
		else {
			print "User $user is allowed to connect from: $host\n";
		}
	}
}

sub priv
{

# This subroutine looks up the grants for the given
# user/host pair.

($user,$host) = @_;

$query = "SHOW GRANTS FOR $user\@$host";
$sth = $dbh->prepare($query);
$sth->execute();

while ($grant = ( $sth->fetchrow() ) ) {
	print "$grant\n";
}

}
